package com.qf.springcloud.filter;

import com.google.common.util.concurrent.RateLimiter;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

/**
 * 限流过滤器，采用令牌桶的方式
 * @author zjw
 */
@Component
public class LimitRateFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.PRE_DECORATION_FILTER_ORDER + 50;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    private final RateLimiter rateLimiter = RateLimiter.create(1);

    @Override
    public Object run() throws ZuulException {
        // 拿到令牌返回true
        if (!rateLimiter.tryAcquire(1)) {
            RequestContext requestContext = RequestContext.getCurrentContext();
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseStatusCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
        }
        return null;
    }
}
